﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Xml;
using Common.Utilities;

namespace Workflows.Components.FALC
{
    /// <summary>
    /// persist workflow design to file system
    /// wfdesign include three parts
    /// 1) binary file (wox)
    /// 2) metadata file (xml)
    /// 3) image file (png)
    /// </summary>
    public class WorkflowDesignFALC
    {
        #region open 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="wfName"></param>
        /// <param name="version"></param>
        /// <param name="designGraph"></param>
        /// <returns></returns>
        public static WorkflowDesign Open(string folderPath, string wfName, Version version, ref Image designGraph)
        {
            string versonName = string.Format(
                "{0}.{1}.{2}.{3}", 
                version.Major, version.Minor,
                version.Build, version.Revision);
            string woxFilePath = Path.Combine(folderPath, wfName + "_" + versonName + ".wox");
            string pngFilePath = Path.Combine(folderPath, wfName + "_" + versonName + ".png");
            WorkflowDesign wfDesign=new WorkflowDesign(woxFilePath);
            designGraph = Image.FromFile(pngFilePath);
            return wfDesign;
        }
        #endregion

        #region save
        /// <summary>
        /// 
        /// </summary>
        /// <param name="wfDesign"></param>
        /// <param name="designGraph"></param>
        /// <param name="folderPath"></param>
        public static void Save(WorkflowDesign wfDesign, Image designGraph, string folderPath)
        {
            string versonName = string.Format(
                "{0}.{1}.{2}.{3}", 
                wfDesign.Version.Major, wfDesign.Version.Minor,
                wfDesign.Version.Build, wfDesign.Version.Revision);
            string fileName = wfDesign.WorkflowName + "_" + versonName;
            string xmlFilePath = Path.Combine(folderPath, fileName + ".xml");
            string woxFilePath = Path.Combine(folderPath, fileName + ".wox");
            string pngFilePath = Path.Combine(folderPath, fileName + ".png");
            XmlDocument xDoc = wfDesign.SaveAsXml();
            xDoc.Save(xmlFilePath);
            if (wfDesign.DesignDocumentFilePath.ToLower() != woxFilePath.ToLower())
                File.Copy(wfDesign.DesignDocumentFilePath, woxFilePath, true);
            designGraph.Save(pngFilePath, System.Drawing.Imaging.ImageFormat.Png);
        }
        #endregion
    }
}
